/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact 824069438@qq.com
 *  
 */
package org.zfes.snowy.im.talent.example;

import java.nio.ByteBuffer;

import com.talent.aio.common.ChannelContext;
import com.talent.aio.common.exception.AioDecodeException;
import com.talent.aio.common.intf.AioHandler;

public class HelloAbsAioHandler  implements AioHandler<Object, HelloPacket, Object>{

	@Override
	public Object handler(HelloPacket packet, ChannelContext<Object, HelloPacket, Object> channelContext)throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public java.nio.ByteBuffer encode(HelloPacket packet, ChannelContext<Object, HelloPacket, Object> channelContext) {
		byte[] body = packet.getBody();
        int bodyLen = 0;
        if (body != null){
            bodyLen = body.length;
        }
 
        int allLen = HelloPacket.HEADER_LENGHT + bodyLen;
        java.nio. ByteBuffer buffer = java.nio.ByteBuffer.allocate(allLen);
        buffer.order(channelContext.getGroupContext().getByteOrder());
 
        buffer.putInt(bodyLen);
 
        if (body != null) {
            buffer.put(body);
        }
        return buffer;
	}

	@Override
	public HelloPacket decode(ByteBuffer buffer, ChannelContext<Object, HelloPacket, Object> channelContext)
			throws AioDecodeException {
		
		int readableLength = buffer.limit() - buffer.position();
        if (readableLength < HelloPacket.HEADER_LENGHT){
            return null;
        }
 
        int bodyLength = buffer.getInt();
 
        if (bodyLength < 0) {
            throw new AioDecodeException("bodyLength [" + bodyLength + "] is not right, remote:" + channelContext.getClientNode());
        }
 
        int neededLength = HelloPacket.HEADER_LENGHT + bodyLength;
        int test = readableLength - neededLength;
        if (test < 0){ // 不够消息体长度(剩下的buffe组不了消息体)
            return null;
        } else {
            HelloPacket imPacket = new HelloPacket();
            if (bodyLength > 0){
                byte[] dst = new byte[bodyLength];
                buffer.get(dst);
                imPacket.setBody(dst);
            }
            return imPacket;
        }
	}
	
}
